<!--
 * @Description:
 * @FilePath: \rs_wms_pc\src\views\invoice\receive\index.vue
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch"
      label-width="68px">
      <el-form-item label="单据编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入单据编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.in_order_status" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="需求总数量" prop="totalQty">
        <el-input
          v-model="queryParams.totalQty"
          placeholder="请输入需求总数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="完成时间" prop="completeTime">
        <el-date-picker clearable
          v-model="queryParams.completeTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择完成时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="采购单号" prop="purchaseOrderNo">
        <el-input
          v-model="queryParams.purchaseOrderNo"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="供应商编码" prop="supplierNo">
        <el-input
          v-model="queryParams.supplierNo"
          placeholder="请输入供应商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("reset") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['bill:receive:add']"-->
<!--        >{{ $t("add") }}</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single||selection[0].status !== 1"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['bill:receive:edit']"-->
<!--        >{{ $t("edit") }}</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-s-claim"-->
<!--          size="mini"-->
<!--          :disabled="!(!single && selection[0].status == 1)"-->
<!--          @click="confirmReceive"-->
<!--          v-hasPermi="['bill.receive:confirm']"-->
<!--        >确定</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['bill:receive:remove']"-->
<!--        >{{ $t("delete") }}</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--          v-hasPermi="['bill:receive:import']"-->
<!--        >{{ $t("import") }}</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['bill:receive:export']">{{ $t("export") }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- :height="calcTableHeight" -->
    <el-table ref="table" v-loading="loading" :data="receiveList" @selection-change="handleSelectionChange"
      highlight-current-row>
      <el-table-column type="selection" width="55" align="center" class-name="leave-alone" />
      <el-table-column label="序号" type="index" width="50" class-name="leave-alone" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <af-table-column label="单据编号" align="center" prop="no" >
        <template slot-scope="scope">
          <span class="link-pop"  @click="rowSelection(scope.row)">{{ scope.row.no }}</span>
        </template>
      </af-table-column>
      <af-table-column label="总数量" align="center" prop="totalQty" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.in_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="完成时间" align="center" prop="completeTime" width="152" /> -->
      <af-table-column label="仓库" align="center" prop="stockCode" />
      <!-- <el-table-column label="供应商编码" align="center" prop="supplierNo" /> -->
      <af-table-column label="货主" align="center" prop="owner" />
      <el-table-column label="库存状态" align="center" prop="stockStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_stock_status" :value="scope.row.stockStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('createUser')" align="center" prop="createBy" min-width="100" />
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" min-width="152" />
      <el-table-column :label="$t('updateUser')" align="center" prop="updateBy" min-width="100" />
      <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" min-width="152" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bill:receive:edit']"
          >{{ $t("edit") }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bill:receive:remove']"
          >{{ $t("delete") }}</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!--   单据明细 -->
    <!-- <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane label="采购收货单明细" name="arrival">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
      <el-tab-pane label="采购收货记录" name="receive">
        <billDetailList ref="billDetailList" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs> -->

    <!-- 添加或修改收货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库" prop="stockCode">
          <el-input v-model.trim="form.stockCode" placeholder="请输入仓库" />
        </el-form-item>
        <el-form-item label="货主" prop="owner">
          <el-input v-model.trim="form.owner" placeholder="请输入货主" />
        </el-form-item>
        <el-form-item label="库存状态" prop="stockStatus">
          <el-select style="width:100%;" v-model="form.stockStatus" placeholder="请输入库存状态">
            <el-option v-for="dict in dict.type.erp_stock_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("sure") }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t("importTip1") }}<em>{{ $t("clickUpload") }}</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>{{ $t("importTip") }}</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">{{ $t("download") }}</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t("sure") }}</el-button>
        <el-button @click="upload.open = false">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>


    <!-- 明细弹窗 -->
    <el-dialog :title="'明细'" :visible.sync="detailModal" width="1000px" append-to-body>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
        <el-tab-pane label="采购收货单明细" name="arrival">
          <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
        <el-tab-pane label="采购收货记录" name="receive">
          <billDetailList ref="billDetailList" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailModal = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { listReceive, getReceive, delReceive, addReceive, updateReceive, completeReceive, confirmReceive, cancelReceive } from "@/api/invoice/receive";
import { listSupplier } from "@/api/basic/supplier"
import { getToken } from "@/utils/auth"
import detailPage from "./detail"
import receiveList from "./receiveList"
import billDetailList from "./billDetailList"

export default {
  name: "Receive",
  dicts: ["in_order_status", "erp_stock_status"],
  components: { detailPage, receiveList, billDetailList },
  mixins: [mixins],
  provide() {
    return {
      refresh: this.getList
    }
  },
  data() {
    return {
      detailModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收货单表格数据
      receiveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        totalQty: null,
        status: null,
        completeTime: null,
        purchaseOrderNo: null,
        supplierNo: null,
        supplierName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseOrderNo: [
          { required: true, message: "采购单号不能为空", trigger: "blur" }
        ],
        supplierNo: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bill/receive/importExcel",
      },
      //传递给订单详情的数据
      orderData: {},
      supplierList: [],
      activeTab: 'arrival',
    };
  },
  created() {
    this.getList();
    this.getListSupplier()
  },
  methods: {
    handleTabClick(value) {
      console.log(value)
    },
    /** 获取供应商列表 */
    getListSupplier() {
      listSupplier({ pageNum: 1, pageSize: 0 }).then((response) => {
        this.supplierList = response.rows
      })
    },
    //行选择
    rowSelection(row) {
      this.detailModal = true
      this.$nextTick(() => {
        this.activeTab = "arrival"
        this.orderData = row
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "收货单导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("bill/receive/importTemplate", {}, `收货单模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 确认 */
    confirmReceive(row) {
      this.reset();
      const id = row.id || this.ids[0];
      this.$modal
        .confirm(this.$t("confirmTip"))
        .then(function () {
          return confirmReceive({ id: id })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => { })
    },
    /** 查询收货单列表 */
    getList() {
      this.loading = true;
      listReceive(this.queryParams).then(response => {
        let orderData = { ...this.orderData }
        this.receiveList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.$nextTick(()=>{
          if(orderData && orderData.id){
            let row = response.rows.find(item => item.id == orderData.id)
            this.$refs.table.setCurrentRow(row);
          }
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        totalQty: null,
        status: 0,
        completeTime: null,
        purchaseOrderNo: null,
        supplierNo: null,
        supplierName: null,
        remark: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.rowSelection({});
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.rowSelection({});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收货单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReceive(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收货单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReceive(this.form).then(response => {
              this.$modal.msgSuccess(this.$t("editSuc"))
              this.open = false;
              this.getList();
            });
          } else {
            addReceive(this.form).then(response => {
              this.$modal.msgSuccess(this.$t("addSuc"))
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delReceive(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t("deleteSuc"))
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bill/receive/export', {
        ids: this.ids,
        ...this.queryParams
      }, `收货单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


